package ejb.bl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.ejb.Remote;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.ejb.embeddable.EJBContainer;

import cart.CartItem;

/**
 * Session Bean implementation class CartBean
 */
@Stateful(name = "CartBean")
@Remote(CartBeanRemote.class)
public class CartBean implements CartBeanRemote {
	int customerId;
	ArrayList<CartItem> contents;

	/**
	 * Default constructor.
	 */
	public CartBean() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void initialize() {
		// TODO Auto-generated method stub
		customerId = 0;
		contents = new ArrayList<CartItem>();
	}

	@Override
	public void initialize(int id) {
		// TODO Auto-generated method stub
		customerId = id;
		contents = new ArrayList<CartItem>();
	}

	@Override
	public void addMusicCd(CartItem newItem) {
		// See if there's already an item like this in the cart
		boolean currIndex = contents.isEmpty();
		if (currIndex) {
			// If the item is new, add it to the cart
			contents.add(newItem);
		} else {
			Boolean itemExists = false;
			for (Iterator it = contents.iterator(); it.hasNext();) {
				Object o = it.next();
				CartItem shop = (CartItem) o;
				if (shop.getitemId() == newItem.getitemId()) {
					shop.update(newItem.getitemId(), newItem.getQty());
					itemExists = true;
				}
			}
			if (!itemExists)
				contents.add(newItem);
		}
	}

	@Override
	public void removeMusicCd(int id) {		
		// TODO Auto-generated method stub
		for (int i = 0; i < contents.size(); i++) {
			Object o = contents.get(i);
			CartItem shop = (CartItem) o;
			if (shop.getitemId() == id) {
				// Remove item
				contents.remove(i);
				break;
			}
		}
	}

	@Override
	public List<CartItem> getContents() {
		// TODO Auto-generated method stub
		return contents;
	}

	@Remove
	@Override
	public void remove() {
		// TODO Auto-generated method stub
		contents = null;
	}

	@Override
	public void resetCart() {
		// TODO Auto-generated method stub
		contents.clear();
	}
}
